//
//  HsDateUtil.m
//  CRM-iPhone
//
//  Created by Mead on 12/18/13.
//  Copyright (c) 2013 hundsun. All rights reserved.
//

#import "HsDateUtil.h"
#import "HsStringUtil.h"

@implementation HsDateUtil

+(BOOL)sameDay:(NSDate*)d1 date:(NSDate*)d2{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:d1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:d2];
    return [comp1 day]   == [comp2 day] && [comp1 month] == [comp2 month] && [comp1 year]  == [comp2 year];
}

+(NSInteger)calculateDay:(NSDate*)d1 date:(NSDate*)d2{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned int unitFlags = NSDayCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags fromDate:d1  toDate: d2 options:0];
    //-24<hours<0,day=-1;0<hours<24,day=0;24<hours<48,day=1
    NSInteger day = [components day];
    return day;
}

+(NSInteger)subtractMin:(NSDate*)d1 date:(NSDate*)d2{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSMinuteCalendarUnit;
    NSDateComponents* comp = [calendar components:unitFlags fromDate:d1 toDate:d2 options:0];
    NSInteger min = abs([comp minute]);
    return min;
}

+(NSDate*) dateFromString:(NSString*)string{
    //2014-08-07 00:00:00
    if (![HsStringUtil isStringEmpty:string] && string.length==19) {
        //pass
    }else{
        return [NSDate date];
    }
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date =[dateFormat dateFromString:string];
    return date;
}

+(NSString*) timeFromDate:(NSString*)string{
    //2014-08-07 00:00:00
    if (![HsStringUtil isStringEmpty:string] && string.length==19) {
        //pass
    }else{
        return @"00:00";
    }
    
    
    NSString *hour = [string substringFromIndex:11];
    hour = [hour substringToIndex:5];
    return hour;
}

+(NSString*) formateDateFromString:(NSString*)date{
    if (![HsStringUtil isStringEmpty:date] && date.length==8) {
        NSMutableString *string = [NSMutableString stringWithString:date];
        [string insertString:@"-" atIndex:4];
        [string insertString:@"-" atIndex:7];
        return string;
    }
    return @"";
}

@end
